<?php
/**
 * @Author:      zk
 * @DateTime:    18-7-23 下午1:56
 * @Description: 申请相关
 */

class OAApply extends Eloquent
{
    protected $table = 'oa_apply';

    /**
     * @Author:      zk
     * @DateTime:    18-7-23 下午1:56
     * @Description: 申请的状态数组
     * @var array
     */
    public static $statusArr = [
        1 => '未提交',
        2 => '审批中',
        3 => '同意',
        4 => '不同意',
        5 => '已撤回',
        6 => '已删除',
    ];
    
    /**
     * @Author:      zk
     * @DateTime:    18-8-7 上午9:45
     * @Description: 允许删除的状态  【 同意、不同意、已撤回 】
     * @var array
     */
    public static $canDeleteStatusArr = [
        3, 4, 5,
    ];

    /**
     * 我的申请列表默认显示的状态   2:审批中;3:同意;4:不同意;5:已撤回;
     * @var array
     */
    public static $activeStatusAll = [
        2, 3, 4, 5,
    ];
    const APPROVAL_USER = 1;        //审批人
    const COPY_USER     = 2;        //抄送人
    const APPROVAL_TRS_USER     = 3;        //接受转批人

    /**
     * 获取我的申请列表 已归档
     * User: yyc
     * Date: 2018/7/31
     * Time: 16:01
     * @param $userId   integer 用户ID
     * @param $search   string  模糊查找条件（摘要）
     * @param $page     integer 当前页码
     * @param $pageSize integer 每页显示条数
     * @param $status   array   审批状态 1:未提交;2:审批中;3:同意;4:不同意;5:已撤回;6:已删除
     * @param $typeId   array|integer   审批类型ID
     * @param $isPage   int   是否需要分页
     * @param $isCount   string   是否获取个人消息
     * @return array|integer
     */
    public static function activeApply($userId, $isPage, $search, $page, $pageSize, $status, $typeId, $isCount)
    {
        $selectArray = [
            'oa_apply.id as applyId', 'form_value as content',
            'oa_apply.apply_number', 'oa_approval_type.name as typeName',
            'oa_approval_model.name as modelName', 'oa_apply.created_at',
            'oa_apply.created_at', 'oa_apply.status', 'my.real_name as myName',
            'oa_apply.hrm_department_id as applyHrmUserId', 'oa_apply.hrm_department as applyName',
            'oa_approval_model.form_set as formSet',
        ];
        $result = OAApply::where('oa_apply.created_by', $userId)
            ->join('oa_approval_model', 'oa_approval_model.id', '=', 'oa_apply.approval_model_id')
            ->join('oa_approval_type', 'oa_approval_type.id', '=', 'oa_apply.approval_type_id')
            //->join('oa_apply_flow as two', 'oa_apply.id', '=', 'two.apply_id')
            //->whereRaw('two.level = oa_apply.level')
            //->where('two.user_type', '=', self::APPROVAL_USER)
            //->join('oa_user as user', 'user.id', '=', 'two.user_id')
            ->join('oa_user as my', 'my.id', '=', 'oa_apply.created_by')
            ->orderByRaw('oa_apply.status asc, oa_apply.created_at desc , oa_apply.apply_number desc')
            ->select($selectArray);
        if (!empty($typeId)) {
            $result->whereIn('oa_apply.approval_type_id', $typeId);
        }

        if (!empty($status)) {
            $result->whereIn('oa_apply.status', $status);
        } else {
            $result->whereIn('oa_apply.status', self::$activeStatusAll);
        }

        if (!empty($search)) {
            $result->where('oa_apply.form_value', 'like', '%'. trim(json_encode($search, JSON_UNESCAPED_UNICODE), "\"") . '%');
        }

        $resultTemp = clone $result;

        //分页要的数据
        if (!empty($isPage)) {
            $resultLast = $result->groupBy('applyId')->get()->toArray();
        } else {
            $resultLast = $result->groupBy('applyId')->skip($pageSize * ($page - 1))->take($pageSize)->get()->toArray();
        }

        if (empty($resultLast)) {
            return [];
        }

        $count = '';
        $countResult = $resultTemp->get()->toArray();
        if (empty($countResult)) {
            return [];
        }

        //分页后需要发送前台的数据applyId
        $applyId = array_unique(array_column($resultLast, 'applyId'));

        //分页查询之前的所有数据
        if (empty($count)) {
            $count = count(array_unique(array_column($countResult, 'applyId')));
        }

        if (empty($isCount)) {
            return $count;
        }

        //添加其他的审批人信息
        $approval = OAApplyFlow::whereIn('oa_apply.id', $applyId)
            ->whereIn('oa_apply_flow.user_type', [self::APPROVAL_USER, self::APPROVAL_TRS_USER])
            ->join('oa_apply', 'oa_apply.level', '=', 'oa_apply_flow.level')
            ->whereRaw('oa_apply.id = oa_apply_flow.apply_id')
            ->whereIn('oa_apply_flow.status', [1, 2, 3, 4])
            ->join('oa_user', 'oa_user.id', '=', 'oa_apply_flow.user_id')
            ->select([
                'oa_user.real_name as userName', 'oa_apply_flow.apply_id', 'oa_user.id',
                'oa_apply_flow.op_type as opType', 'oa_apply_flow.status'
            ])
            ->get()->toArray();
        return self::processingActiveData($resultLast, $applyId, $count, $approval);
        //return self::processingData($resultLast, $applyId, $count);
        //暂时不在使用状态转化
        //return self::processingStatus($resultLast);
    }

    /**
     * 获取我的审批列表
     * User: yyc
     * Date: 2018/8/1
     * Time: 11:01
     * @param $userId   integer 用户ID
     * @param $search   string  模糊查找条件（摘要）
     * @param $page     integer 当前页码
     * @param $pageSize integer 每页显示条数
     * @param $status   int   审批状态  1:待处理;2:审批中;3:同意;4:不同意;5:已撤回;空的时候是全部
     * @param $typeId   array|integer   审批类型ID
     * @param $isCount   string   是否获取个人消息
     * @return array|integer
     */
    public static function passiveApply($userId, $search, $page, $pageSize, $status, $typeId, $isCount)
    {
        $selectArray = [
            'oa_apply.apply_number', 'oa_approval_type.name as typeName',
            'two.level as flowLevel', 'oa_approval_model.form_set as formSet',
            'oa_approval_model.name as modelName', 'oa_apply.created_at',
            'form_value as content', 'oa_apply.created_at', 'two.status as flowStatus',
            'oa_apply.level as applyLevel', 'oa_apply.status as applyStatus', 'my.real_name as myName',
            'approval_way', 'oa_apply.id as applyId', 'two.op_type as opType',
        ];
        $result = OAApply::where('two.user_id', $userId)
            ->join('oa_approval_model', 'oa_approval_model.id', '=', 'oa_apply.approval_model_id')
            ->join('oa_approval_type', 'oa_approval_type.id', '=', 'oa_apply.approval_type_id')
            ->join('oa_apply_flow as two', 'oa_apply.id', '=', 'two.apply_id')
            ->whereIn('two.user_type', [self::APPROVAL_USER, self::APPROVAL_TRS_USER])
            ->join('oa_user as user', 'user.id', '=', 'two.user_id')
            ->join('oa_user as my', 'my.id', '=', 'oa_apply.created_by')
            ->orderByRaw('oa_apply.status asc, two.status asc, oa_apply.created_at desc , oa_apply.apply_number desc, two.level desc')
            ->select($selectArray);
        if (!empty($typeId)) {
            $result->where('oa_apply.approval_type_id', $typeId);
        }

        if (!empty($status) && $status == 1) {
            $result->whereRaw('two.level = oa_apply.level')
                ->where('two.status', '=', 1)
                ->whereIn('oa_apply.status', [2]);
        }

        if (!empty($status) && $status == 2) {
            $result->whereRaw('two.level <= oa_apply.level')
                ->where('two.status', '=', 2)
                ->whereIn('oa_apply.status', [2]);
        }

        if (!empty($status) && $status == 3) {
            $result->where('two.status', '=', 2)->whereIn('oa_apply.status', [3]);
        }

        if (!empty($status) && $status == 4) {
            $result->whereRaw('two.level <= oa_apply.level')
                ->where('two.status', '=', 2)
                ->whereIn('oa_apply.status', [4]);
        }

        if (!empty($status) && $status == 5) {
            $result->whereRaw('two.level <= oa_apply.level')
                ->where('two.status', '=', 4)
                ->whereIn('oa_apply.status', [5]);
        }

        if (!empty($search)) {
            $result->where('oa_apply.form_value', 'like', '%'. trim(json_encode($search, JSON_UNESCAPED_UNICODE), "\"") . '%');
        }

        if (empty($status)) {
            $result->whereRaw('two.level <= oa_apply.level')->whereIn('oa_apply.status', self::$activeStatusAll)->whereIn('two.status', [1, 2, 3, 4]);
        }

        $resultTemp = clone $result;
        //分页要的数据
        $resultLast = $result->groupBy('applyId')->skip($pageSize * ($page - 1))->take($pageSize)->get()->toArray();

        if (empty($resultLast)) {
            return [];
        }

        $count = '';
        $countResult = $resultTemp->get()->toArray();

        if (empty($countResult)) {
            return [];
        }

        //取消我本人没有审批，但是审批等级已经不在我这等级
        $noNeed = 0;
        if (empty($countResult)) {
            return [];
        } else {
            foreach($countResult as $key => $value) {
                if ($value['opType'] == 0
                    && $value['applyLevel'] > $value['flowLevel']
                    && in_array($value['approval_way'], [2, 3])
                ) {
                    unset($countResult[$key]);
                    $noNeed++;
                }
            }
        }

        //return count(array_unique(array_column($countResult, 'applyId')));
        //分页后需要发送前台的数据apply_id
        $applyId = array_unique(array_column($resultLast, 'applyId'));

        //return count($applyId);
        //分页查询之前的所有数据
        if (empty($count)) {
            $count = count(array_unique(array_column($countResult, 'applyId')));
        }

        if (empty($isCount)) {
            return $count;
        }


        //return $applyId;
        //暂时不用判断审批状态
        /*if (empty($status)) {
            return self::processingType($resultLast, $applyId, $count);
        }*/

        //添加其他的审批人信息
        $approval = OAApplyFlow::whereIn('oa_apply.id', $applyId)
            ->whereIn('oa_apply_flow.user_type', [self::APPROVAL_USER, self::APPROVAL_TRS_USER])
            ->join('oa_apply', 'oa_apply.level', '=', 'oa_apply_flow.level')
            ->whereRaw('oa_apply.id = oa_apply_flow.apply_id')
            ->whereIn('oa_apply_flow.status', [1, 2, 3, 4])
            ->join('oa_user', 'oa_user.id', '=', 'oa_apply_flow.user_id')
            ->select([
                'oa_user.real_name as userName', 'oa_apply_flow.apply_id', 'oa_user.id',
                'oa_apply_flow.op_type as opType', 'oa_apply_flow.status'
            ])
            ->get()->toArray();
        if (empty($status)) {
            $firstData = [];

            $applyId = array_unique(array_column($countResult, 'applyId'));

            foreach ($applyId as $applyValue) {
                foreach ($countResult as $resultValue) {
                    if ($applyValue == $resultValue['applyId']) {
                        $firstData[$applyValue] = $resultValue;
                    }
                }
            }

            $firstData = array_slice($firstData, ($page - 1) * $pageSize, $pageSize);

            $approval = OAApplyFlow::whereIn('oa_apply.id', $applyId)
                ->whereIn('oa_apply_flow.user_type', [self::APPROVAL_USER, self::APPROVAL_TRS_USER])
                ->join('oa_apply', 'oa_apply.level', '=', 'oa_apply_flow.level')
                ->whereRaw('oa_apply.id = oa_apply_flow.apply_id')
                ->whereIn('oa_apply_flow.status', [1, 2, 3, 4])
                ->join('oa_user', 'oa_user.id', '=', 'oa_apply_flow.user_id')
                ->select([
                    'oa_user.real_name as userName', 'oa_apply_flow.apply_id', 'oa_user.id',
                    'oa_apply_flow.op_type as opType', 'oa_apply_flow.status'
                ])
                ->get()->toArray();

            $lastData = [];
            foreach (array_values($firstData) as $userValue) {
                foreach ($approval as $lastValue) {
                    if ($userValue['applyId'] == $lastValue['apply_id']) {
                        unset($lastValue['apply_id']);
                        $userValue['userInfo'][] = $lastValue;
                    }
                }
                $userValue['formSet'] = json_decode($userValue['formSet'], TRUE);
                $userValue['content'] = json_decode($userValue['content'], TRUE);
                $lastData[] = $userValue;
            }

            if (empty($lastData)) {
                return [];
            }

            return [
                'count' => $count,
                'infoAll'  => $lastData,
            ];
        }
        return self::processingActiveData($resultLast, $applyId, $count, $approval);
    }

    /**
     * 处理我的审批数据
     * @param $resultLast
     * @param $applyId
     * @param $count
     * @param $approval
     * @return array
     * @author yyc
     * @date 2018/8/21 16:27
     */
    public static function processingActiveData($resultLast, $applyId, $count, $approval)
    {
        $firstData = [];
        foreach ($applyId as $applyValue) {
            foreach ($resultLast as $resultValue) {
                if ($applyValue == $resultValue['applyId']) {
                    $firstData[$applyValue] = $resultValue;
                }
            }
        }

        $lastData = [];
        foreach (array_values($firstData) as $userValue) {
            foreach ($approval as $lastValue) {
                if ($userValue['applyId'] == $lastValue['apply_id']) {
                    unset($lastValue['apply_id']);
                    $userValue['userInfo'][] = $lastValue;
                }
            }
            $userValue['formSet'] = json_decode($userValue['formSet'], TRUE);
            $userValue['content'] = json_decode($userValue['content'], TRUE);
            $lastData[] = $userValue;
        }

        if (empty($lastData)) {
            return [];
        }

        return [
            'count' => $count,
            'infoAll'  => $lastData,
        ];
    }


    /**
     * 处理审批类型
     * User: yyc
     * Date: 2018/8/1
     * Time: 14:01
     * @param $resultLast
     * @return array
     */
    public static function processingType($resultLast, $applyId, $count)
    {   //flag   (1:待处理;2:审批中;3:同意;4:不同意;5:已撤回;空的时候是全部)
        foreach ($resultLast as &$value) {

            //待处理  审批层次到当前节点但是没有人审批
            if (($value['flowLevel'] == $value['applyLevel'])
                && ($value['flowStatus'] <= 1)
                && ($value['applyStatus'] == 2)
            ) {
                $value['status'] = 1;    //--待处理

            }

            //审批中  审批层次大于等于当前节点但是还没有完全走完整个流程
            if (($value['flowLevel'] <= $value['applyLevel']) &&
                ($value['flowStatus'] == 2) && (in_array($value['applyStatus'], [2]))
            ) {
                $value['status'] = 2;   //--审批中

            }

            //同意 所有审批全部走完并且审批通过，并且当前节点参与审批
            if (($value['flowStatus'] == 2)
                && (in_array($value['applyStatus'], [3]))
                && $value['flowLevel'] <= $value['applyLevel']
            ) {
                $value['status'] = 3;   //--同意
            }

            //不同意  审批不通过，并且当前节点参与审批
            if (($value['flowLevel'] <= $value['applyLevel']) &&
                ($value['flowStatus'] == 2) && (in_array($value['applyStatus'], [4]))
            ) {
                $value['status'] = 4;   //--不同意
            }

            //已撤销  审批已撤回，并且当前节点参与审批
            if (($value['flowLevel'] <= $value['applyLevel'])
                && ($value['flowStatus'] == 4)
                && ($value['applyStatus'] == 5)
            ) {
                $value['status'] = 5;   //--已撤回
            }

        }

        return self::processingData($resultLast, $applyId, $count);

    }

    /**
     * 获取抄送给我列表
     * User: yyc
     * Date: 2018/8/1
     * Time: 16:01
     * @param $userId   integer 用户ID
     * @param $search   string  模糊查找条件（摘要）
     * @param $page     integer 当前页码
     * @param $pageSize integer 每页显示条数
     * @param $status   array   审批状态 1:未提交;2:审批中;3:同意;4:不同意;5:已撤回;6:已删除
     * @param $typeId   array|integer   审批类型ID
     * @param $isCount   string   是否获取用户消息
     * @return array|integer
     */
    public static function copyApply($userId, $search, $page, $pageSize, $status, $typeId, $isCount)
    {
        $selectArray = [
            'oa_apply.apply_number', 'oa_approval_type.name as typeName',
            'copy.real_name as copyUserName', 'oa_apply.id as applyId',
            'oa_approval_model.name as modelName', 'oa_apply.created_at',
            'form_value as content', 'oa_apply.created_at', 'oa_apply.status', 'my.real_name as myName',
            'oa_approval_model.form_set as formSet',
        ];
        $result = OAApply::where('one.user_id', $userId)
            ->join('oa_approval_model', 'oa_approval_model.id', '=', 'oa_apply.approval_model_id')
            ->join('oa_approval_type', 'oa_approval_type.id', '=', 'oa_apply.approval_type_id')
            //->join('oa_apply_flow as two', 'oa_apply.id', '=', 'two.apply_id')
            //->whereRaw('two.level = oa_apply.level')
            //->where('two.user_type', '=', self::APPROVAL_USER)
            ->join('oa_apply_flow as one', 'one.apply_id', '=', 'oa_apply.id')
            ->where('one.user_type', '=', self::COPY_USER)
            //->join('oa_user as user', 'user.id', '=', 'two.user_id')
            ->join('oa_user as my', 'my.id', '=', 'oa_apply.created_by')
            ->join('oa_user as copy', 'copy.id', '=', 'one.user_id')
            ->orderByRaw('oa_apply.status asc, oa_apply.created_at desc , oa_apply.apply_number desc')
            ->select($selectArray);
        if (!empty($typeId)) {
            $result->whereIn('oa_apply.approval_type_id', $typeId);
        }

        if (!empty($status)) {
            $result->whereIn('oa_apply.status', $status);
        } else {
            $result->whereIn('oa_apply.status', self::$activeStatusAll);
        }

        if (!empty($search)) {
            $result->where('oa_apply.form_value', 'like', '%'. trim(json_encode($search, JSON_UNESCAPED_UNICODE), "\"") . '%');
        }
        $resultTemp = clone $result;

        //分页要的数据
        $resultLast = $result->groupBy('applyId')->skip($pageSize * ($page - 1))->take($pageSize)->get()->toArray();

        if (empty($resultLast)) {
            return [];
        }

        $count = '';
        $countResult = $resultTemp->get()->toArray();
        if (empty($countResult)) {
            return [];
        }

        //分页后需要发送前台的数据applyId
        $applyId = array_unique(array_column($resultLast, 'applyId'));

        //分页查询之前的所有数据
        if (empty($count)) {
            $count = count(array_unique(array_column($countResult, 'applyId')));
        }

        if (empty($isCount)) {
            return $count;
        }
        //添加其他的审批人信息
        $approval = OAApplyFlow::whereIn('oa_apply.id', $applyId)
            ->whereIn('oa_apply_flow.user_type', [self::APPROVAL_USER, self::APPROVAL_TRS_USER])
            ->join('oa_apply', 'oa_apply.level', '=', 'oa_apply_flow.level')
            ->whereRaw('oa_apply.id = oa_apply_flow.apply_id')
            ->whereIn('oa_apply_flow.status', [1, 2, 3, 4])
            ->join('oa_user', 'oa_user.id', '=', 'oa_apply_flow.user_id')
            ->select([
                'oa_user.real_name as userName', 'oa_apply_flow.apply_id', 'oa_user.id',
                'oa_apply_flow.op_type as opType', 'oa_apply_flow.status'
            ])
            ->get()->toArray();
        return self::processingActiveData($resultLast, $applyId, $count, $approval);
        //return $resultLast;
        //return self::processingStatus($resultLast);
    }

    /**
     * 处理返回审批状态  已归档  我的申请 抄送给我
     * User: yyc
     * Date: 2018/8/1
     * Time: 16:30
     * @param $resultLast
     * @return array
     */
    public static function processingStatus($resultLast)
    {
        $array = range(1, 6);
        foreach ($resultLast as &$value) {
            if (in_array($value['status'], $array)) {
                $value['status'] = self::$statusArr[$value['status']];
            }
        }

        return self::processingData($resultLast, '', '');
    }

    /**
     * User: yyc
     * Date: 2018/8/1
     * Time: 10:01
     * 处理返回数据
     * @param $resultLast
     * @param $count
     * @param $applyId
     * @return array
     */
    public static function processingData($resultLast, $applyId, $count = '')
    {
        $firstData = [];
        foreach ($applyId as $applyValue) {
            foreach ($resultLast as $resultValue) {
                if ($applyValue == $resultValue['applyId']) {
                    $firstData[$applyValue] = $resultValue;
                }
            }
        }

        $lastData = [];
        foreach (array_values($firstData) as $userValue) {
            unset($userValue['userId']);
            unset($userValue['userName']);
            foreach ($resultLast as $lastValue) {
                if ($userValue['applyId'] == $lastValue['applyId']) {
                    $userValue['userInfo'][] = [
                        'id' => $lastValue['userId'],
                        'userName' => $lastValue['userName'],
                    ];
                }
            }
            $userValue['formSet'] = json_decode($userValue['formSet'], TRUE);
            $userValue['content'] = json_decode($userValue['content'], TRUE);
            $lastData[] = $userValue;
        }

        if (empty($lastData)) {
            return [];
        }

        return [
            'count' => $count,
            'infoAll'  => $lastData,
        ];
    }

    /**
     * 获取审批详情
     * @param $applyId
     * @param $userId
     * @param $type
     * @return array|mixed
     */
    public static function infoApply($applyId, $userId, $type)
    {
        $selectArray = [
            'oa_apply.apply_number', 'oa_approval_type.name as typeName', 'user.real_name as userName',
            'oa_approval_model.name as modelName', 'oa_apply.created_at', 'user.id as userId',
            'form_value as content', 'oa_apply.created_at', 'oa_apply.status', 'my.real_name as myName',
            'two.level as passiveLevel', 'two.status as flowStatus', 'two.op_type as flowType',
            'oa_apply.status as applyStatus', 'oa_apply.level as applyLevel', 'my.id as myId',
            'oa_apply.hrm_department as departmentName', 'oa_apply.hrm_department_id as departmentId',
            'user.hrm_user_id as approvalHrmUserId', 'two.approval_way as flowApprovalWay',
            'oa_approval_model.desc', 'oa_approval_model.form_set as formSet', 'oa_apply.id as applyId',
            'oa_apply.pc', 'oa_apply.wechat', 'oa_apply.email', 'two.postil', 'two.updated_at as cTime',
            'two.op_type as opType', 'oa_approval_model.id',
        ];
        $result = OAApply::where('oa_apply.id', $applyId)
            ->join('oa_approval_model', 'oa_approval_model.id', '=', 'oa_apply.approval_model_id')
            ->join('oa_approval_type', 'oa_approval_type.id', '=', 'oa_apply.approval_type_id')
            ->join('oa_apply_flow as two', 'oa_apply.id', '=', 'two.apply_id')
            ->whereIn('two.user_type', [self::APPROVAL_USER, self::APPROVAL_TRS_USER])
            ->whereIn('two.status', [1, 2, 3, 4])
            ->join('oa_user as user', 'user.id', '=', 'two.user_id')
            ->orderBy('passiveLevel')
            ->join('oa_user as my', 'my.id', '=', 'oa_apply.created_by')
            ->select($selectArray);
        $resultLast = $result->get()->toArray();

        if (empty($resultLast)) {
            return [];
        }

        if (empty($type) || in_array($type, [1, 3])) {
            return self::processingInfo($resultLast, self::getCopyInfo($applyId), '');
        }

        $myInfo = OAApplyFlow::whereIn('user_type', [1, 3])
            ->leftJoin('oa_apply', 'oa_apply.id', '=', 'oa_apply_flow.apply_id')
            ->where('oa_apply_flow.status', '=', 1)
            ->where('oa_apply.id', '=', $applyId)
            ->where('oa_apply_flow.user_id', '=', $userId)
            ->get()->toArray();

        return self::processingInfo($resultLast, self::getCopyInfo($applyId), $myInfo);
    }

    /**
     * 根据审批编号获取抄送人信息
     * @param $applyId
     * @return mixed
     */
    public static function getCopyInfo($applyId)
    {
        $selectArray = [
            'user.real_name as copyName', 'user.id as copyUserId', 'user.hrm_user_id as copyHrmUserId',
        ];
        $result = OAApplyFlow::where('oa_apply_flow.apply_id', '=', $applyId)
            ->where('oa_apply_flow.user_type', '=', self::COPY_USER)
            ->join('oa_user as user', 'user.id', '=', 'oa_apply_flow.user_id')
            ->select($selectArray)
            ->get()
            ->toArray();
        if (empty($result)) {
            return [];
        }
        //获取抄送人部门信息
        $copyHrmInfo = HrmUser::getUserInfoByIdArray(array_unique(array_column($result, 'copyHrmUserId')));

        if (empty($copyHrmInfo)) {
            return [];
        }

        //添加抄送人部门信息
        foreach ($result as &$resultValue) {
            foreach ($copyHrmInfo as $hrmValue) {
                if ($resultValue['copyHrmUserId'] == $hrmValue['approvalHrmUserId']) {
                    $resultValue['copyHrmUserId'] = $hrmValue['approvalHrmUserId'];
                    $resultValue['copyHrmName'] = $hrmValue['approvalHrmName'];
                    $resultValue['copyHrmId'] = $hrmValue['approvalHrmId'];
                }
            }
        }

        return $result;
    }

    /**
     * 根据审批编号获取审批人信息
     * @param $applyId
     * @param $level
     * @return mixed
     */
    public static function getApprovalUserInfo($applyId, $level = '')
    {
        $selectArray = [
            'user.user_name as approvalName', 'user.id as approvalUserId', 'apply.user_name as applyName',
            'user.hrm_user_id as approvalHrmUserId', 'user.id as approvalOaUserId',
            'oa_apply.created_by as applyUserId', 'oa_apply.hrm_department_id as applyHrmDepartmentId',
            'oa_apply.hrm_department as applyDepartment',
        ];

        $result = OAApply::where('oa_apply.id', '=', $applyId)
            ->leftJoin('oa_apply_flow', 'oa_apply_flow.apply_id', '=', 'oa_apply.id')
            ->where('oa_apply_flow.user_type', '=', self::APPROVAL_USER)
            ->leftJoin('oa_user as user', 'user.id', '=', 'oa_apply_flow.user_id')
            ->leftJoin('oa_user as apply', 'apply.id', '=', 'oa_apply.created_by')
            ->select($selectArray)
            ->get()
            ->toArray();

        if (empty($level)) {
            $result->where('oa_apply_flow.level', '=', 'oa_apply.level');
        } else {
            $result->where('oa_apply_flow.level', '=', $level);
        }
        if (empty($result)) {
            return [];
        }

        //获取审批人部门信息
        $approvalHrmInfo = HrmUser::getUserInfoByIdArray(array_unique(array_column($result, 'approvalHrmUserId')));

        $applyName = array_unique(array_column($result, 'applyName'));
        $applyUserId = array_unique(array_column($result, 'applyUserId'));
        $applyHrmDepartmentId = array_unique(array_column($result, 'applyHrmDepartmentId'));
        $applyDepartment = array_unique(array_column($result, 'applyDepartment'));

        if (empty($approvalHrmInfo)) {
            return [];
        }

        //添加审批人部门信息
        foreach ($result as &$resultValue) {
            foreach ($approvalHrmInfo as $hrmValue) {
                if ($resultValue['approvalHrmUserId'] == $hrmValue['approvalHrmUserId']) {
                    $resultValue['approvalHrmUserId'] = $hrmValue['approvalHrmUserId'];
                    $resultValue['approvalName'] = $hrmValue['approvalHrmName'];
                    $resultValue['approvalHrmId'] = $hrmValue['approvalHrmId'];
                }
            }
        }

        return [
            'approvalInfo' => $result,
            'applyInfo' => [
                'applyName' => $applyName[0],
                'applyUserId' => $applyUserId[0],
                'applyHrmDepartmentId' => $applyHrmDepartmentId[0],
                'applyDepartment' => $applyDepartment[0],
            ],
        ];
    }

    /**
     * 根据申请编号获取抄送人、审批人、申请人的部门信息
     * @param $applyId
     * @param $level
     * @return array
     */
    public static function getAllUserInfo($applyId, $level = '')
    {
        return array_merge(['copyUserInfo' => self::getCopyInfo($applyId)],
            self::getApprovalUserInfo($applyId, $level)
        );
    }

    /**
     * 获取每一层级的审批人信息
     * @param $resultLast      array    申请详情
     * @param $copyUserInfo    array    抄送人信息
     * @param $myInfo    string    我本人信息
     * @return mixed
     */
    public static function processingInfo($resultLast, $copyUserInfo, $myInfo = '')
    {
        $passiveLevel = array_unique(array_column($resultLast, 'passiveLevel'));
        $content = array_unique(array_column($resultLast, 'content'));
        $formSet = array_unique(array_column($resultLast, 'formSet'));
        $typeName = array_unique(array_column($resultLast, 'typeName'));
        $modelName = array_unique(array_column($resultLast, 'modelName'));
        $created_at = array_unique(array_column($resultLast, 'created_at'));
        $applyStatus = array_unique(array_column($resultLast, 'applyStatus'));
        $applyLevel = array_unique(array_column($resultLast, 'applyLevel'));
        $departmentId = array_unique(array_column($resultLast, 'departmentId'));
        $departmentName = array_unique(array_column($resultLast, 'departmentName'));
        $myName = array_unique(array_column($resultLast, 'myName'));
        $myId = array_unique(array_column($resultLast, 'myId'));
        $applyId = array_unique(array_column($resultLast, 'applyId'));
        $applyNumber = array_unique(array_column($resultLast, 'apply_number'));
        $approvalHrmUserId = array_unique(array_column($resultLast, 'approvalHrmUserId'));
        $desc = array_unique(array_column($resultLast, 'desc'));
        $wechat = array_unique(array_column($resultLast, 'wechat'));
        $pc = array_unique(array_column($resultLast, 'pc'));
        $email = array_unique(array_column($resultLast, 'email'));
        $firstData = [];

        //获取审批人信息
        $approvalUserInfo = HrmUser::getUserInfoByIdArray($approvalHrmUserId);

        //添加抄送人信息到审批流程数据
        foreach ($resultLast as &$approvalUserValue) {
            foreach ($approvalUserInfo as $infoValue) {
                if ($infoValue['approvalHrmUserId'] == $approvalUserValue['approvalHrmUserId']) {
                    $approvalUserValue['approvalHrmId'] = $infoValue['approvalHrmId'];
                    $approvalUserValue['approvalHrmName'] = $infoValue['approvalHrmName'];
                }
            }
        }

        //将申请详情按照审批等级进行分组
        foreach ($passiveLevel as $applyValue) {
            foreach ($resultLast as $resultValue) {
                if ($applyValue == $resultValue['passiveLevel']) {
                    $firstData[$applyValue][] = [
                        'id' => $resultValue['userId'],
                        'userName' => $resultValue['userName'],
                        'flowStatus' => $resultValue['flowStatus'],
                        'flowType' => $resultValue['flowType'],
                        'approvalHrmId' => $resultValue['approvalHrmId'],
                        'approvalHrmName' => $resultValue['approvalHrmName'],
                        'approvalHrmUserId' => $resultValue['approvalHrmUserId'],
                        'flowApprovalWay' => $resultValue['flowApprovalWay'],
                        'postil' => $resultValue['postil'],
                        'cTime' => $resultValue['cTime'],
                        'flowLevel' => $applyValue,
                        'opType' => $resultValue['opType'],
                    ];
                }
            }

        }

        if (!empty($myInfo)) {
            $myInfo = 1;
        } else {
            $myInfo = '';
        }
        //审批信息返回信息格式
        $lastData = [
            'level' => array_values($firstData),
            'infoAll' => [
                'content' => json_decode($content[0], TRUE),
                'formSet' => json_decode($formSet[0], TRUE),
                'typeName' => $typeName[0],
                'modelName' => $modelName[0],
                'created_at' => $created_at[0],
                'applyStatus' => $applyStatus[0],
                'applyLevel' => $applyLevel[0],
                'departmentId' => $departmentId[0],
                'departmentName' => $departmentName[0],
                'myName' => $myName[0],
                'applyId' => $applyId[0],
                'apply_number' => $applyNumber[0],
                'myId' => $myId[0],
                'desc' => $desc[0],
                'wechat' => $wechat[0],
                'pc' => $pc[0],
                'email' => $email[0],
                'myInfo' => $myInfo,
            ],
            'copyUserInfo' => $copyUserInfo,
            'copyHrmUserId' => array_column($copyUserInfo, 'copyHrmUserId'),
        ];

        return $lastData;
        /** TODO 需要添加各个审批层级的审批状态需要打开 */
        //return  self::allApplyStatus($lastData, $applyStatus[0], $applyLevel[0]);
    }

    /**
     * 判断每一层级审批状态以及审批人（当前哪一个审批人已经审批）  *******暂不开放*******
     * @param $resultData   array   当前条审批信息
     * @param $applyStatus  int     审批状态
     * @param $applyLevel   int     审批条件
     * @return mixed
     */
    public static function allApplyStatus($resultData, $applyStatus, $applyLevel)
    {
        foreach ($resultData['level'] as $keyApplyLevel => &$valueApplyUserInfo) {
            if ($applyStatus == 0) {
                $userInfo = [];
                foreach ($valueApplyUserInfo as $userValue) {
                    $userInfo[] = $userValue;
                }
                $valueApplyUserInfo = [
                    'status' => '该申请出错',
                    'userInfo' => $userInfo,
                ];
                continue;
            }

            if ($applyStatus == 1) {
                $userInfo = [];
                foreach ($valueApplyUserInfo as $userValue) {
                    $userInfo[] = $userValue;
                }
                $valueApplyUserInfo = [
                    'status' => '申请人尚未提交',
                    'userInfo' => $userInfo,
                ];
                continue;
            }

            if ($applyStatus == 2) {
                if ($keyApplyLevel < $applyLevel) {
                    foreach ($valueApplyUserInfo as $userValue) {
                        if ($userValue['flowStatus'] == 2) {
                            $valueApplyUserInfo = [
                                'status' => '同意',
                                'userInfo' => [],
                            ];
                            $valueApplyUserInfo['userInfo'][] = $userValue;
                            break;
                        }
                    }
                }

                if ($keyApplyLevel == $applyLevel) {
                    $userInfo = [];
                    foreach ($valueApplyUserInfo as $userValue) {
                        $userInfo[] = $userValue;
                    }
                    $valueApplyUserInfo = [
                        'status' => '待审批',
                        'userInfo' => $userInfo,
                    ];
                }

                if ($keyApplyLevel > $applyLevel) {
                    $userInfo = [];
                    foreach ($valueApplyUserInfo as $userValue) {
                        $userInfo[] = $userValue;
                    }
                    $valueApplyUserInfo = [
                        'status' => '',
                        'userInfo' => $userInfo,
                    ];
                }
                continue;

            }

            if ($applyStatus == 3) {
                foreach ($valueApplyUserInfo as $userValue) {
                    if ($userValue['flowStatus'] == 2) {
                        $valueApplyUserInfo = [
                            'status' => '同意',
                            'userInfo' => [],
                        ];
                        $valueApplyUserInfo['userInfo'][] = $userValue;
                        break;
                    }
                }

                continue;
            }

            if ($applyStatus == 4) {
                if ($keyApplyLevel < $applyLevel) {
                    foreach ($valueApplyUserInfo as $userValue) {
                        if ($userValue['flowStatus'] == 2) {
                            $valueApplyUserInfo = [
                                'status' => '同意',
                                'userInfo' => [],
                            ];
                            $valueApplyUserInfo['userInfo'][] = $userValue;
                            break;
                        }
                    }

                }

                if ($keyApplyLevel == $applyLevel) {
                    foreach ($valueApplyUserInfo as $userValue) {
                        if ($userValue['flowStatus'] == 2 && $userValue['flowType'] == 2) {
                            $valueApplyUserInfo = [
                                'status' => '不同意',
                                'userInfo' => [],
                            ];
                            $valueApplyUserInfo['userInfo'][] = $userValue;
                            break;
                        }
                    }
                }

                if ($keyApplyLevel > $applyLevel) {
                    $userInfo = [];
                    foreach ($valueApplyUserInfo as $userValue) {
                        $userInfo[] = $userValue;
                    }
                    $valueApplyUserInfo = [
                        'status' => '',
                        'userInfo' => $userInfo,
                    ];
                }

            }

            if ($applyStatus == 5) {
                if ($keyApplyLevel < $applyLevel) {
                    foreach ($valueApplyUserInfo as $userValue) {
                        if ($userValue['flowStatus'] == 2) {
                            $valueApplyUserInfo = [
                                'status' => '同意',
                                'userInfo' => [],
                            ];
                            $valueApplyUserInfo['userInfo'][] = $userValue;
                            break;
                        }
                    }
                }

                if ($keyApplyLevel == $applyLevel) {
                    foreach ($valueApplyUserInfo as $userValue) {
                        if ($userValue['flowStatus'] == 2 && $userValue['flowType'] == 2) {
                            $valueApplyUserInfo = [
                                'status' => '不同意',
                                'userInfo' => [],
                            ];
                            $valueApplyUserInfo['userInfo'][] = $userValue;
                            break;
                        }
                    }
                }

                if ($keyApplyLevel > $applyLevel) {
                    $userInfo = [];
                    foreach ($valueApplyUserInfo as $userValue) {
                        $userInfo[] = $userValue;
                    }
                    $valueApplyUserInfo = [
                        'status' => '',
                        'userInfo' => $userInfo,
                    ];
                }

                continue;
            }

        }

        return $resultData;
    }

    /**
     * 处理审批
     * User: yyc
     * Date: 2018/8/3
     * Time: 14:01
     * @param $applyId          string      申请编号
     * @param $userIds          array       当前等级审批人的id
     * @param $flowApprovalWay  integer     审批方式(1:单人审批;2:会签;3:或签;)
     * @param $applyLevel       integer     审批等级
     * @param $userId           integer     当前用户的id
     * @param $flowType         integer     同意还是不同意  (1:同意;2:不同意;)
     * @param $postil            string      审批意见
     * @return array
     */
    public static function agreeOrNo($applyId, $userIds, $flowApprovalWay, $applyLevel, $userId, $flowType, $postil)
    {
        $errorInfo = ['code' => 0, 'msg' => 'ok'];
        $time = Common::num2DateTime(time());
        $applyData['updated_at'] = $time;
        $applyData['updated_by'] = $userId;
        $selectLevel = OAApplyFlow::select(['oa_apply_flow.id'])
            ->where('oa_apply_flow.level', '=', $applyLevel + 1 )
            ->where('oa_apply_flow.apply_id', '=', $applyId)
            ->first();

        $flowOtherData = [];
        $flowMyData = [];
        if (!empty($postil)) {
            $flowMyData['postil'] = $postil;
        }
        DB::beginTransaction();
        $isOverCurrentLevel = TRUE;                //当前等级是否审批结束
        $isNeedNextApprovalNews = FALSE;         //是否需要向下一级审批人发送消息
        $isOver = FALSE;                        //判断整个流程事是否结束
        if ($flowType == 2) {

            $applyData['status'] = 4;           //申请表中数据处理--不同意

            $flowOtherData['status'] = 3;       //他人已审批
            $flowOtherData['updated_at'] = $time;       //他人已审批
            $flowOtherData['updated_by'] = $userId;       //他人已审批
            $flowMyData['status'] = 2;          //本人已审批
            $flowMyData['op_type'] = 2;         //本人不同意
            $flowMyData['updated_at'] = $time;         //本人不同意

            if ($flowApprovalWay == 2) {        //会签不同意
                $flowOtherData = [];
            }

        }

        if ($flowType == 1) {                   //同意审批的情况
            if (empty($selectLevel)) {          //没有下一级 -- 审批结束了
                $applyData['status'] = 3;       //审批已同意
            } else {
                $applyData['level'] = $applyLevel + 1;
                unset($applyData['updated_by']);        //没有结束不需要更改
            }

            $flowMyData['updated_at'] = $time;
            if ($flowApprovalWay == 1) {        //单人审批
                $flowMyData['status'] = 2;      //本人已审批
                $flowMyData['op_type'] = 1;     //本人同意

            }

            if (!empty($selectLevel) && $flowApprovalWay == 1) {
                //单人审批已同意并且还有下一级审批时   添加申请人和抄送人  && 多个下一级审批人相同消息不同推送人
                $isNeedNextApprovalNews = TRUE;
            }

            if (empty($selectLevel) && $flowApprovalWay == 1) {
                //  单人审批已同意并且没有下一级审批时   添加申请人和抄送人消息
                $isOver = TRUE;
            }

            //TODO  会签判断是否所有人都已经同意   需要测试
            if ($flowApprovalWay == 2) {        //会签
                //其他人不同意或者还没有审批，则不能到下一个审批等级
                $selectOtherStatus = OAApplyFlow::select('oa_apply_flow.id')
                    ->where('oa_apply_flow.user_type', '=', 1)
                    ->where('oa_apply_flow.apply_id', '=', $applyId)
                    ->where('oa_apply_flow.level', '=', $applyLevel)
                    ->whereIn('oa_apply_flow.user_id', $userIds)
                    ->whereIn('oa_apply_flow.op_type', [0])
                    ->whereIn('oa_apply_flow.status', [1])
                    ->get()
                    ->toArray();
            }

            $flowMyData['status'] = 2;      //本人已审批
            $flowMyData['op_type'] = 1;     //本人同意

            //$selectOtherStatus  所有人都同意--才可以向其他人发出审批消息
            if (empty($selectLevel) && ($flowApprovalWay == 2) && (empty($selectOtherStatus))) {
                $isOverCurrentLevel = TRUE;
                $isNeedNextApprovalNews = FALSE;
                $isOver = TRUE;
            }

            if (!empty($selectOtherStatus)) {
                $isOverCurrentLevel = FALSE;
            }

            if (empty($selectLevel) && ($flowApprovalWay == 2) && (!empty($selectOtherStatus))) {
                $isNeedNextApprovalNews = FALSE;
                $isOver = FALSE;
                $applyData = [];
            }

            if (!empty($selectLevel) && ($flowApprovalWay == 2) && (empty($selectOtherStatus))) {
                //会签审批已同意并且没有下一级审批时   添加申请人和抄送人  && 多个下一级审批人相同消息不同推送人
                $isOver = TRUE;
            }

            if ($flowApprovalWay == 3) {        //或签
                $flowMyData['status'] = 2;      //本人已审批
                $flowMyData['op_type'] = 1;     //本人同意
                $flowOtherData['status'] = 3;   //他人已审批
                $flowOtherData['updated_at'] = $time;   //他人已审批
                $flowOtherData['updated_by'] = $userId;   //他人已审批
            }

            if (empty($selectLevel) && $flowApprovalWay == 3) {
                //或签审批已同意并且还有下一级审批时   添加申请人和抄送人  && 多个下一级审批人相同消息不同推送人
                $isNeedNextApprovalNews = TRUE;
            }

            if (!empty($selectLevel) && $flowApprovalWay == 3) {
                //或签审批已同意并且没有下一级审批时   添加申请人和抄送人消息
                $isOver = FALSE;
            }

        }

        //其审批人信息不为空
        if (!empty($flowOtherData) && !empty($userIds)) {
            if(!(OAApplyFlow::where('oa_apply_flow.level', '=', $applyLevel)
                ->where('oa_apply_flow.apply_id', '=', $applyId)
                ->whereIn('oa_apply_flow.user_id', $userIds)
                ->whereIn('oa_apply_flow.user_type', [1, 3])
                ->where('oa_apply_flow.status', '=', 1)
                ->update($flowOtherData))){
                DB::rollBack();
                $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                return $errorInfo;
            }
        }

        //修改我的状态（当前审批人）
        if(!(OAApplyFlow::where('oa_apply_flow.level', '=', $applyLevel)
            ->where('oa_apply_flow.apply_id', '=', $applyId)
            ->whereIn('oa_apply_flow.user_type', [1, 3])
            ->where('oa_apply_flow.user_id', $userId)
            ->where('oa_apply_flow.status', '=', 1)
            ->update($flowMyData))){
            DB::rollBack();
            $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
            return $errorInfo;
        }

        //修改申请的状态
        if (!empty($applyData)) {
            if(!(OAApply::where('oa_apply.level', '=', $applyLevel)
                ->where('oa_apply.id', '=', $applyId)->update($applyData))){
                DB::rollBack();
                $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                return $errorInfo;
            }
        }

        //消息最后发送
        if ($flowType == 2) {
            //不同意时向申请人和抄送人发送消息
            $applyNews = OANewsNotice::addNewsToApplyPeople($applyId, 4, $userId);
            if (!$applyNews) {
                DB::rollBack();
                $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');

                return $errorInfo;
            }
            $copyNews = OANewsNotice::addNewsToCc($applyId, 4, $userId);
            if (!$copyNews) {
                DB::rollBack();
                $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                return $errorInfo;
            }
        }
        if ($flowType == 1) {
            if ($isNeedNextApprovalNews == FALSE  && $isOver == FALSE && $isOverCurrentLevel == TRUE) {
                $applyNews = OANewsNotice::addNewsToApplyPeople($applyId);
                if (!$applyNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
                $copyNews = OANewsNotice::addNewsToCc($applyId);
                if (!$copyNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
            }

            if ($isNeedNextApprovalNews == FALSE  && $isOver == TRUE && $isOverCurrentLevel == TRUE) {
                $applyNews = OANewsNotice::addNewsToApplyPeople($applyId, 3);
                if (!$applyNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
                $copyNews = OANewsNotice::addNewsToCc($applyId, 3);
                if (!$copyNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
            }

            if ($isNeedNextApprovalNews == TRUE  && $isOver == FALSE && $isOverCurrentLevel == TRUE) {
                $applyNews = OANewsNotice::addNewsToApplyPeople($applyId);
                if (!$applyNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
                $copyNews = OANewsNotice::addNewsToCc($applyId);
                if (!$copyNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
                $approvalNews = OANewsNotice::addNewsToApprover($applyId);
                if (!$approvalNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
            }

            /*if ($isNeedNextApprovalNews == TRUE  && $isOver == TRUE && $isOverCurrentLevel == TRUE) {

                $applyNews = OANewsNotice::addNewsToApplyPeople($applyId, 3, $userId);
                if (!$applyNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
                $copyNews = OANewsNotice::addNewsToCc($applyId, 3, $userId);
                if (!$copyNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
                $approvalNews = OANewsNotice::addNewsToApprover($applyId, '', $userId);
                if (!$approvalNews) {
                    DB::rollBack();
                    $errorInfo = Lang::get('oa_error.apply_controller_status_error_212004');
                    return $errorInfo;
                }
            }*/
        }


        DB::commit();

        return $errorInfo;
    }
}
